package com.bra.receiver;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

import com.bra.MainActivity;
import com.bra.bean.ReceiverMsg;
import com.bra.utils.Contacts;
import com.bra.utils.JsonUtils;
import com.bra.utils.SPHelper;
import com.google.gson.Gson;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import cn.jpush.android.api.JPushInterface;

/**
 * 自定义接收器
 * 
 * 如果不定义这个 Receiver，则：
 *  1) 默认用户会打开主界面 
 *  2) 接收不到自定义消息
 */
@SuppressWarnings("unused")
public class JupushReceiver extends BroadcastReceiver {
	private static final String TAG = "JPush";
	private List<ReceiverMsg> receive_list;
	private Gson gson;
	private JsonUtils juti;
	private String receiver;
	private HashMap<String, List<ReceiverMsg>> data;
	private int no_read;
	@Override
	public void onReceive(Context context, Intent intent) {
		gson = new Gson();
		juti = new JsonUtils();
		data = new HashMap<String, List<ReceiverMsg>>();
		Bundle bundle = intent.getExtras();
		if (JPushInterface.ACTION_REGISTRATION_ID.equals(intent.getAction())) {
			String regId = bundle
					.getString(JPushInterface.EXTRA_REGISTRATION_ID);

		} else if (JPushInterface.ACTION_MESSAGE_RECEIVED.equals(intent
				.getAction())) {
			Log.d(TAG,"[MyReceiver] 接收到推送下来的自定义消息: "
							+ bundle.getString(JPushInterface.EXTRA_MESSAGE));
			processCustomMessage(context, bundle);

		} else if (JPushInterface.ACTION_NOTIFICATION_RECEIVED.equals(intent
				.getAction())) {
			Log.d(TAG, "[MyReceiver] 接收到推送下来的通知");
			receivingNotification(context, bundle);

		} else if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent
				.getAction())) {
			Log.d(TAG, "[MyReceiver] 用户点击打开了通知");
			//打开自定义的Activity
        	Intent i = new Intent(context, MainActivity.class);
        	i.putExtras(bundle);
        	//i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        	i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP );
        	context.startActivity(i);

		} else if (JPushInterface.ACTION_RICHPUSH_CALLBACK.equals(intent
				.getAction())) {
			Log.d(TAG,"[MyReceiver] 用户收到到RICH PUSH CALLBACK: "
							+ bundle.getString(JPushInterface.EXTRA_EXTRA));
		} else if (JPushInterface.ACTION_CONNECTION_CHANGE.equals(intent
				.getAction())) {
			boolean connected = intent.getBooleanExtra(
					JPushInterface.EXTRA_CONNECTION_CHANGE, false);
			Log.w(TAG, "[MyReceiver]" + intent.getAction()
					+ " connected state change to " + connected);
		} else {
			Log.d(TAG, "[MyReceiver] Unhandled intent - " + intent.getAction());
		}
	}

	@SuppressWarnings({ "static-access" })
	private void receivingNotification(final Context context, Bundle bundle) {
		// 标题
		String title = bundle
				.getString(JPushInterface.EXTRA_NOTIFICATION_TITLE);
		// 内容
		String extras = bundle.getString(JPushInterface.EXTRA_EXTRA);//这个获取不到值
		receiver = SPHelper.readString(context, Contacts.JPUSH_MSG);
		no_read = SPHelper.readInt(context, Contacts.JPUSH_NOREAN, 0);
		if (receiver == null) {
			receive_list = new ArrayList<ReceiverMsg>();
		} else {
			receive_list = juti.fromJson(receiver, ReceiverMsg.class,"msg_list");
		}
		ReceiverMsg msg = new ReceiverMsg();
		msg.is_read = "0";
		msg.push_content = juti.getJsonStr(extras, "content");
		msg.push_time = juti.getJsonStr(extras, "time");
		msg.push_title = title;
		receive_list.add(msg);
		System.out.println(title+"=="+extras);
		// receive_list.
		Collections.reverse(receive_list); // 倒序排列
		data.put("msg_list", receive_list);
		final String json = gson.toJson(data);
		new Thread(new Runnable() {
			@Override
			public void run() {
				SPHelper.saveInt(context, Contacts.JPUSH_NOREAN, no_read + 1);
				SPHelper.saveString(context, Contacts.JPUSH_MSG, json);
			}
		}).start();
		if (MainActivity.isForeground) {
			Intent msgIntent = new Intent(MainActivity.MESSAGE_RECEIVED_ACTION);
			msgIntent.putExtra(MainActivity.KEY_MESSAGE, extras);
			context.sendBroadcast(msgIntent);
		}
	}

	// send msg to MainActivity
	@SuppressWarnings("static-access")
	private void processCustomMessage(final Context context, Bundle bundle) {
		receiver = SPHelper.readString(context, Contacts.JPUSH_MSG);
		no_read = SPHelper.readInt(context, Contacts.JPUSH_NOREAN, 0);
		if (receiver == null) {
			receive_list = new ArrayList<ReceiverMsg>();
		} else {
			receive_list = juti.fromJson(receiver, ReceiverMsg.class,"msg_list");
		}
		// bundle.get
		String message = bundle.getString(JPushInterface.EXTRA_MESSAGE);
		ReceiverMsg msg = new ReceiverMsg();
		msg.is_read = "0";
		msg.push_content = juti.getJsonStr(message, "content");
		msg.push_time = juti.getJsonStr(message, "time");
		msg.push_title = juti.getJsonStr(message, "title");
		receive_list.add(msg);
		// receive_list.
		Collections.reverse(receive_list); // 倒序排列
		data.put("msg_list", receive_list);
		final String json = gson.toJson(data);
		new Thread(new Runnable() {
			@Override
			public void run() {
				SPHelper.saveInt(context, Contacts.JPUSH_NOREAN, no_read + 1);
				SPHelper.saveString(context, Contacts.JPUSH_MSG, json);
			}
		}).start();
		if (MainActivity.isForeground) {
			Intent msgIntent = new Intent(MainActivity.MESSAGE_RECEIVED_ACTION);
			msgIntent.putExtra(MainActivity.KEY_MESSAGE, message);
			context.sendBroadcast(msgIntent);
		}
	}
}
